import { BASE_URL, TIME_OUT } from './request/config'
import BaseAxios from './request/index'
import type { RequestConfig } from './request/types'
import { Message } from '@arco-design/web-vue'
import { getToken, removeToken } from '@/utils/auth'
const BaseRequest = new BaseAxios({
  baseURL: BASE_URL,
  timeout: TIME_OUT,
  interceptors: {
    requestInterceptor(config) {
      const isToken = (config.headers || {}).isToken === false
      const token = getToken()
      if (token && !isToken) {
        config.headers['Authorization'] = `Bearer ${token}`
      }
      // 去除空字符串
      if (config.method === 'get' && config.params) {
        Object.keys(config.params).forEach((key) => {
          if (config.params[key] === '') {
            delete config.params[key]
          }
        })
      }

      return config
    },
    requestInterceptorCatch(error) {
      return error
    },
    responseInterceptor(res) {
      return new Promise((resolve) => {
        return resolve(res)
      })
    },
    responseInterceptorCatch(error) {
      // 拿到状态码
      const code = error.response?.status
      if (code === 401) {
        // 401 未授权
        removeToken()
        window.location.reload()
        Message.error(error.response.data.error || '系统未知错误')
      } else {
        Message.error(error.response?.data.error || '系统未知错误')
      }
    },
  },
})
export const request = <T = any>(config: RequestConfig) => {
  return BaseRequest.request<T>(config)
}
export default BaseRequest
